package business;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.Query.CustomParameter;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Where;

@SuppressWarnings("serial")
public class GDataOnGAEJServlet extends HttpServlet {

	private static final Logger LOG = Logger.getLogger(GDataOnGAEJServlet.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String thisUrl = request.getRequestURI();
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		String query = request.getQueryString();

		if (query == null) {
			String scope = "http://www.google.com/calendar/feeds/";
			String hostedDomain = "default";
			boolean secure = false;
			boolean session = true;

			String authSubUrl = AuthSubUtil.getRequestUrl(hostedDomain, thisUrl, scope, secure, session);

			out.println("<p>ログイン認証　<a href=\"" + authSubUrl + "\">こちらから</a>");
		} else {
			String singleUseToken = AuthSubUtil.getTokenFromReply(query);
			LOG.info("singleUseToken=" + singleUseToken);

			try {
				String sessionToken;
				sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null);
				LOG.info("sessionToken=" + sessionToken);
				
				CalendarService calendarService = new CalendarService("GDataOnGAEJ");
				calendarService.setAuthSubToken(sessionToken, null);

				URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/private/full");
				CalendarQuery calendarQuery = new CalendarQuery(feedUrl);

				GregorianCalendar today_start = new GregorianCalendar(TimeZone.getTimeZone("Asia/Tokyo"), Locale.JAPAN);
				today_start.set(GregorianCalendar.HOUR_OF_DAY, 0);
				today_start.set(GregorianCalendar.MINUTE, 0);
				today_start.set(GregorianCalendar.SECOND, 0);
				today_start.set(GregorianCalendar.MILLISECOND, 0);
				today_start.set(GregorianCalendar.HOUR, 9);

				GregorianCalendar today_end = (GregorianCalendar) today_start.clone();
				today_end.add(GregorianCalendar.DATE, 1);
				today_end.add(GregorianCalendar.MILLISECOND, -1);

				calendarQuery.setMinimumStartTime(new DateTime(today_start.getTime()));
				calendarQuery.setMaximumStartTime(new DateTime(today_end.getTime()));

				calendarQuery.addCustomParameter(new CustomParameter("orderby", "starttime"));

				out.println("Getting Calendar Entries...(" + today_start.getTime().toString() + "～" + today_end.getTime().toString() + ")<br />");

				CalendarEventFeed resultFeed = calendarService.query(calendarQuery, CalendarEventFeed.class);

				List<CalendarEventEntry> entries = resultFeed.getEntries();

				for (CalendarEventEntry entry : entries) {
					List<When> eventTimes = entry.getTimes();

					String eventTime = "";
					if (!eventTimes.isEmpty()) {
						When when = eventTimes.get(0);
						eventTime = when.getStartTime().toUiString() + "～" + when.getEndTime().toString();
					}

					List<Where> locations = entry.getLocations();
					String eventLocation = "";
					if (locations.isEmpty()) {
						Where where = locations.get(0);
						eventLocation = where.getLabel() + "," + where.getValueString() + "," + where.getRel();
					}

					System.out.print("<br />タイトル=" + entry.getTitle().getPlainText());
					System.out.print(" 説明=" + entry.getTextContent().getContent().getPlainText());
					System.out.print(" 日時=" + eventTime);
					System.out.println(" 場所=" + eventLocation);

					entry.setTitle(new PlainTextConstruct("クラウド（Servlet）から書き換えましたよ！すごい！！！"));
					URL editUrl = new URL(entry.getEditLink().getHref());
					calendarService.update(editUrl, entry);
				}

				System.out.println("<br /><br />Total Entries : " + entries.size());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
